package com.gomro.galaxy.foundation.bi.acquisition;

import cn.gomro.cloud.core.common.utils.GomroExceptionUtils;
import com.gomro.galaxy.foundation.bi.domain.enumerater.AcquirePlan;
import com.gomro.galaxy.foundation.bi.domain.enumerater.BiAcquirePlan;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.Date;
//采集服务
@Slf4j
@Service
public class AcquisitionService implements ApplicationContextAware {

    private ApplicationContext context;
    private JobLauncher jobLauncher;

    @SneakyThrows//此注解 用来代替 try  catch
    public AcquisitionService(JobRepository jobRepository) {

        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();

        jobLauncher.setJobRepository(jobRepository);
        jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
        jobLauncher.afterPropertiesSet();

        this.jobLauncher = jobLauncher;
    }

    /**
     * 运行采集
     *
     * @param acquirePlan 采集计划
     * @param ver         版本
     * @return 状态
     */
    public boolean run(@NonNull String acquirePlan, @NonNull String ver) {

        try {

            JobParameters jobParameters = new JobParametersBuilder()
                    .addDate("version", new Date())
                    .addString("ver", ver)
                    .toJobParameters();

            String beanName = "";
            //当计划是Bi数据同步计划
            for (BiAcquirePlan a : BiAcquirePlan.values()) {
                if (a.name().equals(acquirePlan)) {
                    beanName = BiAcquirePlan.valueOf(acquirePlan).beanName;//bi采集计划
                    break;
                }
            }
            //当计划是基础数据同步计划
            if ("".equals(beanName)) {
                beanName = AcquirePlan.valueOf(acquirePlan).beanName;//基础表采集计划中的beanName
            }
            Job job = (Job) context.getBean(beanName);
            jobLauncher.run(job, jobParameters);//启动器点运行 （步骤，步骤参数）
            return true;
        } catch (Exception e) {
            GomroExceptionUtils.error(e, acquirePlan, ver);
        }

        return false;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {

        this.context = context;
    }
}
